package rjp.solver;

import java.util.Random;

import rjp.map.SantaMap;
import rjp.mutation.MakeALongestMutation;
import rjp.mutation.Mutation;
import rjp.mutation.ReverseSegmentMutation;
import rjp.solution.Solution;

public class ReverseSegmentsweepSolver implements Solver{

	private Solution solution;
	private Random random;
	private SantaMap map;
	private int maxImprovements=Integer.MAX_VALUE;

	public ReverseSegmentsweepSolver(SantaMap map)
	{
		this.solution=(new OrderedSolver()).solve(map);
		this.random=new Random();
		this.map=map;
	}
	
	public ReverseSegmentsweepSolver(SantaMap map, Solution startSolution)
	{
		this.solution=startSolution;
		this.random=new Random();
		this.map=map;
	}
	
	public void setMaxImprovements(int maxImprovements)
	{
		this.maxImprovements=maxImprovements;
	}
	
	private void align()
	{
		MakeALongestMutation mut=new MakeALongestMutation(this.map);
		mut.mutate(this.solution);
	}

	@Override
	public Solution solve(SantaMap map) throws Exception {
		this.align();
		int improvements=0;
		float prevscore=Float.MAX_VALUE;
		for (int i=map.size()-2; i>=0; i--)
		{
			for(int j=map.size()-1;j>i;j--)
			{
				Mutation mut= new ReverseSegmentMutation(i, j, map);
				if(mut.solutionImprovement(this.solution)>=-0.1 && mut.isLegal(this.solution))
				{
//					System.out.println(solution);
					
					mut.mutate(solution);
//					System.out.println(solution);
					System.out.println("Improvements "+improvements);
					System.out.println("Improve "+i+" "+j+" "+solution.getScore());
					System.out.println(solution.isLegal()+" "+improvements+" "+(prevscore>solution.getScore()));
					prevscore=solution.getScore();
					this.align();
					improvements++;
					if(improvements==this.maxImprovements)
					{
						break;
					}
				}
			}
			if(improvements==this.maxImprovements)
			{
				break;
			}
		}
		return solution;
	}


}
